/*
 * Demoiselle Framework
 * Copyright (C) 2011 SERPRO
 * ----------------------------------------------------------------------------
 * This file is part of Demoiselle Framework.
 * 
 * Demoiselle Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not,  see <http://www.gnu.org/licenses/>
 * or write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA  02110-1301, USA.
 * ----------------------------------------------------------------------------
 * Este arquivo é parte do Framework Demoiselle.
 * 
 * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou
 * modificá-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação
 * do Software Livre (FSF); na versão 2 da Licença.
 * 
 * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
 * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
 * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/GPL em português
 * para maiores detalhes.
 * 
 * Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título
 * "LICENCA.txt", junto com esse programa. Se não, acesse o Portal do Software Público
 * Brasileiro no endereço www.softwarepublico.gov.br ou escreva para a Fundação do Software
 * Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
 
 * @author Tarcizio Vieira Neto (tarcizio.vieira@owasp.org) <a href="http://www.serpro.gov.br">SERPRO</a>
 * @created 2011
 */

package br.gov.frameworkdemoiselle.security.filter.request;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.owasp.appsensor.AttackDetectorUtils;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Logger;
import org.owasp.esapi.StringUtilities;
import org.owasp.esapi.filters.SecurityWrapperRequest;
import org.owasp.esapi.filters.SecurityWrapperResponse;

import br.gov.frameworkdemoiselle.security.filter.wrapper.BlackListSecurityWrapperRequest;


/**
 * This class was based on org.owasp.esapi.filters.SecurityWrapper from 
 * OWASP ESAPI.
 * 
 * This filter wraps the incoming request and outgoing response and overrides
 * many methods with safer versions. Many of the safer versions simply validate
 * parts of the request or response for unwanted characters before allowing the
 * call to complete. Some examples of attacks that use these
 * vectors include request splitting, response splitting, and file download
 * injection. Attackers use techniques like CRLF injection and null byte injection
 * to confuse the parsing of requests and responses.
 * <p/>
 * <b>Example Configuration #1 (Default Configuration allows /WEB-INF):</b>
 * <pre>
 * &lt;filter&gt;
 *    &lt;filter-name&gt;SecurityFilter&lt;/filter-name&gt;
 *    &lt;filter-class&gt;br.gov.frameworkdemoiselle.security.filter.request.SecurityFilter&lt;/filter-class&gt;
 * &lt;/filter&gt;
 * </pre>
 * <p/>
 * <b>Example Configuration #2 (Allows /servlet)</b>
 * <pre>
 * &lt;filter&gt;
 *    &lt;filter-name&gt;SecurityFilterForServlet&lt;/filter-name&gt;
 *    &lt;filter-class&gt;br.gov.frameworkdemoiselle.security.filter.request.SecurityFilter&lt;/filter-class&gt;
 *    &lt;init-param&gt;
 *       &lt;param-name&gt;allowableResourceRoot&lt;/param-name&gt;
 *       &lt;param-value&gt;/servlet&lt;/param-value&gt;
 *    &lt;/init-param&gt;
 * &lt;/filter&gt;
 * </pre>
 *  
 */
public class SecurityFilter implements Filter {

    private final Logger logger = ESAPI.getLogger("SecurityWrapper");

    /**
     * This is the root path of what resources this filter will allow a RequestDispatcher to be dispatched to. This
     * defaults to WEB-INF as best practice dictates that dispatched requests should be done to resources that are
     * not browsable and everything behind WEB-INF is protected by the container. However, it is possible and sometimes
     * required to dispatch requests to places outside of the WEB-INF path (such as to another servlet).
     *
     * See <a href="http://code.google.com/p/owasp-esapi-java/issues/detail?id=70">http://code.google.com/p/owasp-esapi-java/issues/detail?id=70</a>
     * and <a href="https://lists.owasp.org/pipermail/owasp-esapi/2009-December/001672.html">https://lists.owasp.org/pipermail/owasp-esapi/2009-December/001672.html</a>
     * for details.
     */
    private String allowableResourcesRoot = "WEB-INF";

    private String mode = "log";
    
    private boolean checkXSS = false;	
    private boolean checkSQLinjection = false;
    
    private boolean noCacheHeader = false;
        
    
    public void init(FilterConfig filterConfig) {
    	this.allowableResourcesRoot = StringUtilities.replaceNull( filterConfig.getInitParameter( "allowableResourcesRoot" ), allowableResourcesRoot );
    	
    	// modes are "log", "skip", "sanitize", "throw"        
        String modeParam = filterConfig.getInitParameter("mode"); 
    	if (modeParam.matches("log|skip|sanitize|throw"))
    		mode = modeParam;
    	
    	checkXSS = filterConfig.getInitParameter("xssCheck").equalsIgnoreCase("true");
    	checkSQLinjection = filterConfig.getInitParameter("sqlInjectionCheck").equalsIgnoreCase("true");
    	noCacheHeader = filterConfig.getInitParameter("noCacheHeader").equalsIgnoreCase("true");
    }
    
    /**
     *
     * @param request
     * @param response
     * @param chain
     * @throws java.io.IOException
     * @throws javax.servlet.ServletException
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest)) {
            chain.doFilter(request, response);
            return;
        }

        try {
            HttpServletRequest hrequest = (HttpServletRequest)request;
            HttpServletResponse hresponse = (HttpServletResponse)response;

            BlackListSecurityWrapperRequest secureRequest = new BlackListSecurityWrapperRequest(hrequest, checkXSS, checkSQLinjection);                       
            
            SecurityWrapperResponse secureResponse = new SecurityWrapperResponse(hresponse, mode);

            // Set the configuration on the wrapped request
            secureRequest.setAllowableContentRoot(allowableResourcesRoot);

            ESAPI.httpUtilities().setCurrentHTTP(secureRequest, secureResponse);

            chain.doFilter(ESAPI.currentRequest(), ESAPI.currentResponse());
            
            // set up response with content type
			ESAPI.httpUtilities().setContentType( hresponse );
            
			// set no-cache headers on every response
            // only do this if the entire site should not be cached
            // otherwise you should do this strategically in your controller or actions
            if (noCacheHeader)
            	ESAPI.httpUtilities().setNoCacheHeaders( hresponse );
            
        } catch (Exception e) {
            logger.error( Logger.SECURITY_FAILURE, "Error in SecurityWrapper: " + e.getMessage(), e );
            request.setAttribute("message", e.getMessage() );
        } finally {
            ESAPI.httpUtilities().clearCurrent();
        }
    }

    /**
     *
     */
    public void destroy() {
		// no special action
	}
	
}

